/*
 * Server.cpp
 *
 *  Created on: 03.12.2012
 *      Author: zheka
 */

#include "Server.hpp"
#include "util/ProxyException.hpp"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <iostream>
Server::Server(int port) :
		port(port) {
}

void Server::start() {
	if ((socketFileDescriptor = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
		throw ProxyException("[Server] Can't create server socket!");
	}
	fcntl(socketFileDescriptor, F_SETFL, O_NONBLOCK);
	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);
	addr.sin_addr.s_addr = htonl(INADDR_ANY);
std::cerr<<"Server fd="<<socketFileDescriptor<<std::endl;
	if (bind(socketFileDescriptor, (struct sockaddr *) &addr,
			sizeof(struct sockaddr)) != 0) {
		throw ProxyException("[Server] Can't bind server socket!");
	}

	if (listen(socketFileDescriptor, 2) != 0) {
		throw ProxyException("[Server] Can't listen server socket!");
	}
}
int Server::accept() {
	int sock;

	if ((sock = ::accept(socketFileDescriptor, NULL, NULL)) == -1) {
		throw ProxyException("[Server] Can't accept incoming connection!");
	}

	/*int optval = 1;
		int optlen = sizeof(optval);
		if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &optval,
				optlen) < 0) {

			throw ProxyException("[Server] Cant setopt!");
		}

		optval = 2000;

				if (setsockopt(socketFileDescriptor, SOL_SOCKET, 18, &optval,
						optlen) < 0) {

					throw ProxyException("[Client] Cant setopt!");
				}*/

	return sock;
}
int Server::getSocketFileDescriptor() {
	return socketFileDescriptor;
}
